//
//  RunTimeViewController.m
//  指纹识别
//
//  Created by lzy on 2018/4/23.
//  Copyright © 2018年 lzy. All rights reserved.
//

#import "RunTimeViewController.h"
#import "Cat.h"
#import <objc/runtime.h>

#import <objc/message.h>

@interface RunTimeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic , strong) UITableView * table;
@property (nonatomic , strong) NSArray *dataArray;

@end

@implementation RunTimeViewController
-(UITableView *)table{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height)];
        _table.delegate = self;
        _table.dataSource = self;
        _table.rowHeight = 44;
    }
    return _table;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"runtime";
    self.dataArray = @[@"消息机制>>",@"方法交换 Method Swizzling>>"];
    [self.view addSubview:self.table];
    // Do any additional setup after loading the view.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [[UITableViewCell alloc]init];
    cell.textLabel.text = self.dataArray[indexPath.row];
    cell.textLabel.textColor = [UIColor blueColor];
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        [self msg];
    }else if(indexPath.row == 1){
        //方法交换 Method Swizzling
        objc_msgSend([Cat new], @selector(eat));
    }
        
}

//消息机制
-(void)msg{
    // 通过类名获取类
    Class catClass = objc_getClass("Cat");
    
    //注意Class实际上也是对象，所以同样能够接受消息，向Class发送alloc消息
    Cat *cat = objc_msgSend(catClass, @selector(alloc));
    
    //发送init消息给Cat实例cat
    cat = objc_msgSend(cat, @selector(init));
    
    //发送eat消息给cat，即调用eat方法
    objc_msgSend(cat, @selector(eat));
    
    //汇总消息传递过程
    objc_msgSend(objc_msgSend(objc_msgSend(objc_getClass("Cat"), sel_registerName("alloc")), sel_registerName("init")), sel_registerName("eat"));
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
